package com.example.stock.service.impl;

import com.example.stock.api.StockApiService;
import com.example.stock.model.StockDailyData;
import com.example.stock.model.StockInfo;
import com.example.stock.service.StockService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 股票服务实现类
 *
 * @author zwg
 * @date 2025/8/5 22:16
 */
@Service
@Slf4j
public class StockServiceImpl implements StockService {

    @Autowired
    private StockApiService stockApiService;

    //@Autowired
    //private RedisTemplate<String, Object> redisTemplate;

    //@Value("${stock.cache.expire-time}")
    //private long cacheExpireTime;

    // Redis键前缀
    private static final String STOCK_INFO_PREFIX = "stock:info:";
    private static final String STOCK_DAILY_DATA_PREFIX = "stock:daily:";

    /**
     * 获取股票基本信息
     *
     * @param code
     */
    @Override
    public StockInfo getStockInfo(String code) {
        // 先从缓存获取
        String cacheKey = STOCK_INFO_PREFIX + code;
        StockInfo stock = null;//(StockInfo) redisTemplate.opsForValue().get(cacheKey);

        if (stock == null) {
            // 缓存未命中，从API获取
            stock = stockApiService.getStockInfo(code);
            if (stock != null) {
                // 存入缓存
                //redisTemplate.opsForValue().set(cacheKey, stock, cacheExpireTime, TimeUnit.SECONDS);
            }
        }

        return stock;
    }

    /**
     * 获取股票某日交易数据
     *
     * @param code
     * @param date
     */
    @Override
    public StockDailyData getStockDailyData(String code, LocalDate date) {
        String cacheKey = STOCK_DAILY_DATA_PREFIX + code + ":" + date.toString();
        StockDailyData dailyData = null;//(StockDailyData) redisTemplate.opsForValue().get(cacheKey);

        if (dailyData == null) {
            dailyData = stockApiService.getStockDailyData(code, date);
            if (dailyData != null) {
                //redisTemplate.opsForValue().set(cacheKey, dailyData, cacheExpireTime, TimeUnit.SECONDS);
            }
        }

        return dailyData;
    }

    /**
     * 获取股票历史交易数据
     *
     * @param code
     * @param startDate
     * @param endDate
     */
    @Override
    public List<StockDailyData> getStockHistoricalData(String code, LocalDate startDate, LocalDate endDate) {
        return stockApiService.getStockHistoricalData(code, startDate, endDate);
    }

    /**
     * 获取市场所有股票
     *
     * @param market
     */
    @Override
    public List<StockInfo> getAllStocks(String market) {
        List<String> codes = stockApiService.getAllStockCodes(market);
        List<StockInfo> stocks = new ArrayList<>();

        for (String code : codes) {
            StockInfo stock = getStockInfo(code);
            if (stock != null) {
                stocks.add(stock);
            }
        }

        return stocks;
    }

    /**
     * 更新股票数据
     */
    @Override
    public void updateStockData() {
        log.info("开始更新股票数据...");

        // 更新沪市股票数据
        updateMarketData("SH");

        // 更新深市股票数据
        updateMarketData("SZ");

        log.info("股票数据更新完成");
    }

    /**
     * 更新指定市场的股票数据
     */
    private void updateMarketData(String market) {
        List<String> codes = stockApiService.getAllStockCodes(market);
        LocalDate today = LocalDate.now();

        for (String code : codes) {
            try {
                // 更新股票基本信息
                StockInfo stock = stockApiService.getStockInfo(code);
                if (stock != null) {
                    //redisTemplate.opsForValue().set(STOCK_INFO_PREFIX + code, stock, cacheExpireTime, TimeUnit.SECONDS);
                }

                // 更新今日交易数据
                StockDailyData dailyData = stockApiService.getStockDailyData(code, today);
                if (dailyData != null) {
                    String cacheKey = STOCK_DAILY_DATA_PREFIX + code + ":" + today.toString();
                    //redisTemplate.opsForValue().set(cacheKey, dailyData, cacheExpireTime, TimeUnit.SECONDS);
                }

                Thread.sleep(100); // 避免请求过于频繁
            } catch (Exception e) {
                log.error("更新股票 {} 数据失败: {}", code, e.getMessage());
            }
        }
    }
}
